package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
    @Autowired
    private CategoryBrandService categoryBrandService;
    @Override
    public PageDTO<BrandDTO> pageQuery(Integer page, Integer rows, String key) {
        IPage<Brand> ipage=new Page<>(page,rows);
        Boolean condition = StringUtils.isNotBlank(key);
        page(ipage,new QueryWrapper<Brand>().like(condition,"name",key)
        .or()
        .eq(condition,"letter",key));
        return new PageDTO<>(ipage.getTotal(),ipage.getPages(),BrandDTO.convertEntityList(ipage.getRecords()));
    }

    @Override
    public BrandDTO queryBrandById(Long id) {

        return new BrandDTO(getById(id));
    }

    @Override
    @Transactional
    public void addBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        save(brand);
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());
}

    private void saveCategoryBrand(List<Long> categoryIds, Long id) {
        List<CategoryBrand> categoryBrands = categoryIds
                .stream()
                .map(categoryId -> CategoryBrand.of(categoryId, id))
                .collect(Collectors.toList());
        this.categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        updateById(brand);
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",brand.getId()));
        saveCategoryBrand(brandDTO.getCategoryIds(),brand.getId());
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        //TODO
        removeById(id);
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",id));
    }
}